import React from 'react';
import { Form, Input, Select, Button, message, Breadcrumb, Upload } from 'antd';
import { useLocation } from 'react-router-dom';
import { NEWS_MENU_TYPE_ENUM } from '../News/type';
import './index.less';

interface NewsFormProps { }

interface NewsFormValues {
  title: string;
  content: string;
  type: string;
}

const { Option } = Select;
const { TextArea } = Input;
const info = {
  "accessKey": "L5VZ0hd6EmEupQBkw956FrX9ugha-NUzCeCDTiOC",
  "secretKey": "cnY6vq3vhFKZMo96Szfr8oeW-kn5L2vdmZZvzU3y",
  "scope": "dlc-space",
  "deadline": 1720977041
}

const NewsForm: React.FC<NewsFormProps> = () => {
  const [form] = Form.useForm<NewsFormValues>();
  // 存放图片 url
  const [imageUrl, setImageUrl] = React.useState('');
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const backType = searchParams.get('backType');
  console.log(backType);
  const [breadcrumbLinks, setBreadcrumbLinks] = React.useState<{ key: string; title: string; href: string }[]>([]);

  React.useEffect(() => {
    let links: { key: string; title: string; href: string }[] = [];
    if (backType === NEWS_MENU_TYPE_ENUM.KEYAN) {
      links = [
        { key: '1', title: '首页', href: '/' },
        { key: '2', title: '科研生活', href: '/#/news?type=KEYAN' },
      ];
    } else if (backType === NEWS_MENU_TYPE_ENUM.HEZUO) {
      links = [
        { key: '1', title: '首页', href: '/' },
        { key: '2', title: '合作交流', href: '/#/news?type=HEZUO' },
      ];
    } else if (backType === NEWS_MENU_TYPE_ENUM.TUANDUI) {
      links = [
        { key: '1', title: '首页', href: '/' },
        { key: '2', title: '团队生活', href: '/#/news?type=TUANDUI' },
      ];
    } else if (backType === NEWS_MENU_TYPE_ENUM.TONGZHI) {
      links = [
        { key: '1', title: '首页', href: '/' },
        { key: '2', title: '通知公告', href: '/#/news?type=TONGZHI' },
      ];
    }
    setBreadcrumbLinks(links);
  }, [backType]);

  const onFinish = (values: NewsFormValues) => {
    console.log('Received values of form: ', values);
    message.success('新闻提交成功！');
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const onFileChange = async ({ fileList }: { fileList: any[] }) => {
    const file = fileList[fileList.length - 1]?.originFileObj;
    if (!file) return;

    try {
      // 获取要上传的图片 url
      // const url = await uploadToOSS(file);
      // setImageUrl(url);
      // form.setFieldsValue({ imageUrl: url });

      form.setFieldValue('imageUrl', 123);
      message.success('图片上传成功');
    } catch (error) {
      message.error('图片上传失败，请重试');
    }
  };

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto' }}>
      <Breadcrumb>
        {breadcrumbLinks.map(link => (
          <Breadcrumb.Item key={link.key}>
            <a href={link.href}>{link.title}</a>
          </Breadcrumb.Item>
        ))}
        <Breadcrumb.Item>创建新闻</Breadcrumb.Item>
      </Breadcrumb>
      <Form
        form={form}
        name="newsForm"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="新闻标题"
          name="title"
          rules={[
            {
              required: true,
              message: '请输入新闻标题!',
            },
          ]}
        >
          <Input placeholder="请输入新闻标题" />
        </Form.Item>

        <Form.Item
          label="新闻类型"
          name="type"
          rules={[
            {
              required: true,
              message: '请选择新闻类型!',
            },
          ]}
        >
          <Select placeholder="请选择新闻类型">
            <Option value={NEWS_MENU_TYPE_ENUM.KEYAN}>科研动态</Option>
            <Option value={NEWS_MENU_TYPE_ENUM.HEZUO}>合作交流</Option>
            <Option value={NEWS_MENU_TYPE_ENUM.TUANDUI}>团队生活</Option>
            <Option value={NEWS_MENU_TYPE_ENUM.TONGZHI}>通知公告</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="新闻图片"
          name="imageUrl"
          rules={[
            {
              required: true,
              message: '请上传图片',
            },
          ]}
        >
          <Upload
            listType="picture-card"
            beforeUpload={() => false} // 阻止默认上传行为
            onChange={onFileChange}
            maxCount={1}
          >
            {imageUrl ? <img src={imageUrl} alt="news image" /> : '+ Upload'}
          </Upload>
        </Form.Item>

        <Form.Item
          label="新闻内容"
          name="content"
          rules={[
            {
              required: true,
              message: '请输入新闻内容!',
            },
          ]}
        >
          <TextArea rows={4} placeholder="请输入新闻内容" />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
          <Button type="primary" htmlType="submit">
            提交新闻
          </Button>
        </Form.Item>
      </Form>
    </div >
  );
};


export default NewsForm;